package com.sm.honkon.ui.fragment.clients_management

import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.sm.honkon.R
import com.sm.honkon.app.base.BaseFragment
import com.sm.honkon.app.event.ReadDataEvent
import com.sm.honkon.app.handle.BottomHandle
import com.sm.honkon.app.utils.CommondData
import com.sm.honkon.app.utils.SerialPortUtil
import com.sm.honkon.databinding.FrgControLogCatBinding
import com.sm.honkon.ui.activity.MainActivity
import com.sm.honkon.ui.adapter.LogcatsAdapter
import com.sm.honkon.ui.adapter.PopWindowAdapter
import com.sm.honkon.ui.fragment.laser_therapy.LaserTherapyFragment
import com.sm.honkon.ui.model.ControlLogCatViewModel
import kotlinx.android.synthetic.main.frg_contro_log_cat.*
import kotlinx.android.synthetic.main.frg_handel_clients_manager.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class ControlLogCatFragment :
    BaseFragment<ControlLogCatViewModel, FrgControLogCatBinding>() {
    override fun layoutId(): Int = R.layout.frg_contro_log_cat
    val adapter by lazy {
        LogcatsAdapter().apply {
            addChildClickViewIds(R.id.tv_control)
            setOnItemChildClickListener { _, _, position ->
                selectPosition = position
                (activity as MainActivity).controlLogCat.value = data[position]
            }
        }
    }

    val winAdapter by lazy {
        PopWindowAdapter(mViewModel.shouzhen).apply {
            setOnItemClickListener { _, _, position ->
                tv_last_treatment_conetnt.text = data[position]
                mViewModel.user.value?.last_treatment_conetnt = data[position]
                mViewModel.insertUser()
                mPopWindow.dismiss()
            }
        }
    }

    val mPopWindow: PopupWindow by lazy {
        val contentView: View = LayoutInflater.from(requireContext())
            .inflate(R.layout.popwindow, null)
        PopupWindow(
            contentView,
            tv_first_treatment_conetnt.width, ViewGroup.LayoutParams.WRAP_CONTENT, true
        ).apply {
            this.contentView = contentView
            val recyclerView = contentView.findViewById<RecyclerView>(R.id.host_recycle)
            recyclerView.adapter = winAdapter
            //解决5.0以下版本点击外部不消失问题
            isOutsideTouchable = true
            setBackgroundDrawable(BitmapDrawable())
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        arguments?.getLong("userId")?.let {
            mViewModel.user = mViewModel.customerDao.getCustomer(it)
            mViewModel.logcat = mViewModel.logcatDao.getLogCatById(it)
        }
        mDatabind.model = mViewModel
        mDatabind.handle = BottomHandle(nav())

        recycler_view.apply {
            adapter = this@ControlLogCatFragment.adapter
        }

        tv_last_treatment_conetnt.setOnClickListener { showPopWindow() }

        tv_goto_zhiliao.setOnClickListener {
            (activity as MainActivity).curCustomerEntity.postValue(mViewModel.user.value)
            (activity as MainActivity).controlLogCat.postValue(adapter.getItemOrNull(adapter.selectPosition))
            if (LaserTherapyFragment.isControl) {
                nav().popBackStack(R.id.laserTherapyFragment, false)
            } else {
                laserTherapy()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDataRead(event: ReadDataEvent) {
        event.data.let {
            if (isVisible.not() || it[0].and(0xFF) != 0x01)
                return@onDataRead
            val type = it[1].and(0xFF)
            val result = it[3].and(0xFF)
            ToastUtils.showShort("收到数据")
            when (type) {
                0x11 -> {
                    launch?.cancel()
                    if (result == 0x00) {
                        ToastUtils.showShort("联机成功")
                        nav().navigateAction(R.id.action_controlLogCatFragment_to_laserTherapyFragment)
                    } else {
                        ToastUtils.showShort("已断开")
                    }
                    tv_goto_zhiliao.isEnabled = true
                }

            }
        }
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    private fun showPopWindow() {
        mPopWindow.showAsDropDown(tv_last_treatment_conetnt)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.logcat.observe(this) {
            adapter.setNewInstance(it.toMutableList())
        }
    }

    var launch: Job? = null


    fun laserTherapy() {
//            nav().navigateAction(R.id.action_controlLogCatFragment_to_laserTherapyFragment)
        tv_goto_zhiliao.isEnabled = false
        ToastUtils.showShort("正在连接中,请耐心守候")
        SerialPortUtil.sendSerialPort(CommondData.START_CONTROL)
        launch = lifecycleScope.launch(Dispatchers.Main) {
            delay(10_000)
//            CommondData.getInstance().readDataByte(intArrayOf(0x01,0x11,0x00,0x00,0x00,0x00,0xcc,0x33,0xc3,0x3c),0);
            tv_goto_zhiliao.isEnabled = true
            ToastUtils.showShort("连接超时")
        }
    }

}